package dijjer.io.download;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

/**
 * @author ian
 * 
 * To change the template for this generated type comment go to Window - Preferences - Java - Code Generation - Code and
 * Comments
 */
public class DownloaderThread extends Thread {

	public static final int NUM_THREADS = 6;
	static LinkedList pool = new LinkedList();
	static LinkedList jobs = new LinkedList();

	public static void init() {
		final long serialVersionUID = 1L;
		for (int x = 0; x < NUM_THREADS; x++) {
			new DownloaderThread();
		}
	}

	public static void wakeThreads() {
		synchronized (pool) {
			for (Iterator i = pool.iterator(); i.hasNext();) {
				DownloaderThread dt = (DownloaderThread) i.next();
				synchronized (dt) {
					dt.notify();
				}
			}
		}
	}

	public static void addJob(Job job) {
		synchronized (jobs) {
			jobs.add(job);
		}
		wakeThreads();
	}

	public static void removeJob(Job job) {
		synchronized (jobs) {
			jobs.remove(job);
		}
	}
	
	public static LinkedList getActiveJobs() {
		return (LinkedList) jobs.clone();
	}

	boolean killed = false;

	public DownloaderThread() {
		pool.add(this);
		this.start();
	}

	public void run() {
		while (!killed) {
			Job job = null;
			synchronized (jobs) {
				for (ListIterator i = jobs.listIterator(); i.hasNext();) {
					Job j = (Job) i.next();
					if (j.readyForNextTask()) {
						i.remove();
						job = j;
						break;
					}
				}
			}
			if (job != null) {
				job.performNextTask();
				synchronized (jobs) {
					jobs.addLast(job);
				}
			} else {
				synchronized (this) {
					try {
						this.wait(1000);
					} catch (InterruptedException e) {
					}
				}
			}
		}
	}
}

